// 设计用户登录界面

// 关闭VSCode非必要报错
// ignore_for_file: camel_case_types, non_constant_identifier_names, use_build_context_synchronously

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:project_award_statistics/pages/desktop_adwaita/middle_page/middle_page.dart';
import 'package:project_award_statistics/pages/desktop_adwaita/register_page/register_page.dart';
import 'package:project_award_statistics/utils/load_award_info_from_db/load_award_info.dart';
import 'package:project_award_statistics/utils/my_yaru_buttons/my_yaru_button_confirmed.dart';
import 'package:project_award_statistics/utils/my_yaru_buttons/my_yaru_button_normal.dart';
import 'package:project_award_statistics/utils/dialog_yaru_design/login/dialog_login_err_empty.dart';
import 'package:project_award_statistics/utils/dialog_yaru_design/login/dialog_login_err_wrong_passwd.dart';
import 'package:project_award_statistics/utils/load_user_info_from_db/load_user_info.dart';
import 'package:project_award_statistics/utils/load_user_info_from_db/user_model.dart';
import 'package:window_manager/window_manager.dart';

class LoginPage_Desktop extends StatefulWidget {
  const LoginPage_Desktop({super.key});
  @override
  State<LoginPage_Desktop> createState() => _LoginPage_DesktopState();
}

class _LoginPage_DesktopState extends State<LoginPage_Desktop> with TickerProviderStateMixin {
  // 初始化用户名与密码输入的控制器
  var textcontroller_user_name = TextEditingController();
  var textcontroller_password = TextEditingController();

  // 初始化动画总线1
  late AnimationController _animationController_widget1;

  //设置淡入效果控制总线1默认状态下不可见
  bool widget1_isVisible = false;

  //设置淡入效果控制总线2默认状态下不可见
  bool widget2_isVisible = false;

  // 用于检查用户名与对应密码输入是否正确
  Future<bool> is_allow_login(String stu_name, String password) async 
    {
      List<user_info_model> cur_user_info = await DBProvider_UserInfo().get_user_list();
      int i = 0;
      int input_user_point = 0; // input_user_point用于下方循环找到
      bool user_is_exist = false; // user_is_exist用于下方是否在用户数据表中找到对应用户
      for (i = 0; i < cur_user_info.length; i++) {
        if (textcontroller_user_name.text == cur_user_info[i].stu_name) {
          input_user_point = i; // 更新下标
          user_is_exist = true; // 更新开关,表明找到了用户
          break;
        }
      }
      if (user_is_exist) {
        if (textcontroller_password.text ==
            cur_user_info[input_user_point].password) {
          return true; // 用户密码正确就允许登录
        }
      }
      return false; // 否则禁止登录
    }

  // 登录时返回的函数
  void doLogin() async {
    if (textcontroller_user_name.text.isEmpty || textcontroller_password.text.isEmpty) 
      {
        // 如果用户名与密码没输入完,那就返回报错对话框
        showDialog(
          context: context,
          builder: (context) {
            return DialogLoginErrEmpty_Desktop();
          },
        );
      } 
    else if (!await is_allow_login(textcontroller_user_name.text,textcontroller_password.text,)) 
      {
        // 如果用户名与密码输入错误,那就返回报错对话框
        showDialog(
          context: context,
          builder: (context) {
            return DialogLoginErr_WrongPasswd_Desktop(stu_name:textcontroller_user_name.text,);
          },
        );
      } 
    else   // 如果登录正常就先进行数据库初始化,再跳转至页面切换中间件
      {
        await DBProvider_AwardInfo().initDB(textcontroller_user_name.text);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder:
              (context) => PopScope(
                canPop: false, 
                child: MiddlePage_Desktop(stu_name:textcontroller_user_name.text,),
              ),        
          ),
        );
      }
  }

  //覆写父类初始化方法
  @override
  void initState() {
    super.initState();
    _animationController_widget1 = AnimationController(
      duration: Duration(seconds: 1), // 设置动画持续时间
      vsync: this,
    );

    Timer(Duration(seconds: 1), () {
      // 设置淡入控件1时间延迟
      setState(() {
        widget1_isVisible = !widget1_isVisible;
      });
      Timer(Duration(seconds: 1), () {
        // 淡入总线1启动后,启动总线2
        setState(() {
          widget2_isVisible = !widget2_isVisible;
        });
      });
    });

    // 动画,启动!
    _animationController_widget1.forward();
  }

  // 覆写父类的析构函数
  @override
  void dispose() 
    {
      super.dispose();
      // 先停止并释放动画总线1
      _animationController_widget1.stop();
      _animationController_widget1.dispose();
    }

  @override
  Widget build(BuildContext context) {
    // 在页面渲染后更新标题
    WindowManager.instance.setTitle("个人获奖信息查询  --   登录页面");
    // 初始化UI总体框架
    return Scaffold(
      backgroundColor: Colors.white, // 设置背景颜色
      body: Padding(
        padding: EdgeInsets.only(top: 40, left: 80, right: 90), // 设置总布局的边界距离
        child: Column(
          // 第一行显示西北民大校徽
          children: [
            // 显示校徽
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  "lib/images/northwest_minzu_university_icon.png",
                  width: 150,
                  height: 150,
                ),
                const SizedBox(width: 50),
                Text(
                  "西北民族大学",
                  style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold),
                ),
              ],
            ),

            const SizedBox(height: 50),

            Expanded(
              // 设置"吃干净"下面的剩余空间
              child: Row(
                // 设置图片下方总列式布局
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      AnimatedOpacity(
                        // 增加淡入淡出控件
                        opacity: widget1_isVisible ? 1.0 : 0.0,
                        duration: Duration(seconds: 1),
                        child: Text(
                          "您是谁",
                          style: TextStyle(
                            fontSize: 55,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      const SizedBox(height: 40),
                      AnimatedOpacity(
                        // 增加淡入淡出控件
                        opacity: widget2_isVisible ? 1.0 : 0.0,
                        duration: Duration(seconds: 1),
                        child: Text(
                          "请在右侧输入您的姓名与密码",
                          style: TextStyle(fontSize: 28),
                        ),
                      ),
                      const SizedBox(height: 100),    // 控制与底部间距
                    ],
                  ),

                  const SizedBox(width: 0),    // 设置两侧总控件的间距

                  SlideTransition(     // 两文本框是一同进入的
                    position: Tween<Offset>(
                      begin: Offset(2.0, 0),
                      end: Offset.zero,
                    ).animate(
                      CurvedAnimation(
                        parent: _animationController_widget1,
                        curve: Curves.easeInOut,    // 设置特定动画曲线
                      ),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(
                          width: 400,
                          child: TextField(
                            controller: textcontroller_user_name,
                            decoration: InputDecoration(
                              border: OutlineInputBorder(),
                              hintText: " 请在这里输入您的用户名",
                            ),
                          ),
                        ),
                        const SizedBox(height: 40),    // 设置两控件间距离
                        SizedBox(
                          width: 400,
                          child: TextField(
                            controller: textcontroller_password,
                            obscureText: true,    // 设置为true以隐藏输入的文本
                            decoration: InputDecoration(
                              border: OutlineInputBorder(),
                              hintText: " 请在这里输入您的密码",
                            ),
                          ),
                        ),
                        const SizedBox(height: 55),
                        Row(
                          // 列式布局用于放置两按钮
                          children: [
                            SizedBox(
                              height: 40,
                              width: 100,
                              child: MyYaruButton_Normal(
                                text: "注册",
                                onPressed: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder:
                                        (context) => PopScope(
                                          canPop: false,
                                          child: RegisterPage_Desktop(),
                                        ),
                                    ),
                                  );
                                },
                              ),
                            ),
                            const SizedBox(width: 80),
                            SizedBox(
                              height: 40,
                              width: 100,
                              child: MyYaruButton_Confirmed(
                                text: "确认",
                                onPressed: doLogin,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 80),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
